package com.example.mydemo.service.impl;

import com.example.mydemo.entity.Menu;
import com.example.mydemo.entity.MenuRole;
import com.example.mydemo.entity.domain.MenuVO;
import com.example.mydemo.mapper.MenuMapper;
import com.example.mydemo.mapper.MenuRoleMapper;
import com.example.mydemo.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author syf
 * @since 2025-05-28
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    // 定义一个私有的MenuRoleMapper对象，用于操作角色菜单映射表
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private final MenuRoleMapper menuRoleMapper;

    public MenuServiceImpl(MenuRoleMapper menuRoleMapper) {
        this.menuRoleMapper = menuRoleMapper;
    }
//    public static boolean hasDuplicates(List<?> list) {
//        Map<?, Long> countMap = list.stream()
//                .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
//        return countMap.values().stream().anyMatch(count -> count > 1);
//    }

    @Override
    public List<MenuVO> getMenuByRoleId(List<Long> id) {
        // 这里返回的resourceEntityList 没有实现排序
        // 以后 可以考虑下 返回 resourceEntityList之前 根据resource对象的sort进行排序
        // 那么左侧显示的菜单就可以排序了
        List<Menu> resourceEntityList = new ArrayList<>();

        List<MenuRole> roleResourceEntities = new ArrayList<>();
        for (Long roleId : id) {
            List<MenuRole> roleResourceEntities1 = menuRoleMapper.selectMenuByRoleId(roleId);
//            roleResourceEntities = Stream.of(roleResourceEntities1, roleResourceEntities)
//                    .flatMap(Collection::stream).distinct()
//                    .collect(Collectors.toList());
            roleResourceEntities.addAll(roleResourceEntities1);
        }
        // roleResourceEntity里面就是一个中间表 两个字段 roleId resourceId 关联起来

        System.out.println("impl输出测试目录" + roleResourceEntities);
        // 新建一个对象数组继续宁条件判断资源
        // 用for循环遍历，如果i=0且小于资源则菜单资源进行想相加在循环
        if (roleResourceEntities != null && roleResourceEntities.size() > 0) {
            List<MenuVO> noChildrenResourceEntities = new ArrayList<>();
            // 进行资源判断是否为空或者大于0
            for (int i = 0; i < roleResourceEntities.size(); i++) {
                // 获取roleResource(资源中间表)中的resourceId(资源id)
                System.out.println("impl输出测试目录" + roleResourceEntities.get(i).getMenuId());
                Integer menuId = roleResourceEntities.get(i).getMenuId();
                Menu menu = menuMapper.getMenuById(Long.valueOf(menuId));

                MenuVO resourceEntity = MenuVO.convertToVO(menu);
                // 就是根据这个登陆者的roleId 所拥有的资源取出来

                    noChildrenResourceEntities.add(resourceEntity);


            }
            // 使用Map存储所有菜单项
            Map<Integer, MenuVO> menuMap = new HashMap<>();
            for (MenuVO menu : noChildrenResourceEntities) {
                menu.setChild(new ArrayList<>()); // 初始化子菜单列表
                menuMap.put(Math.toIntExact(menu.getMenuId()), menu);
            }

            // 构建树形结构
            List<MenuVO> result = new ArrayList<>();
            for (MenuVO menu : menuMap.values()) {
                int parentId = Math.toIntExact(menu.getParentId());
                // 父节点为0 说明是根节点
                if (parentId == 0) {
                    result.add(menu); // 添加根节点
                } else {
                    MenuVO parent = menuMap.get(parentId);
                    if (parent != null) {
                        parent.getChild().add(menu); // 添加到父节点
                    } else {
                        // 处理游离节点：作为根节点或记录日志
                        result.add(menu);
                    }
                }
            }
            // 菜单排序（按sort字段）
            result.stream().sorted(Comparator.nullsLast(Comparator.comparingInt(MenuVO::getSort)));
            for (MenuVO menu : menuMap.values()) {
                if (!menu.getChild().isEmpty()) {
                    menu.getChild().stream().sorted(Comparator.nullsLast(Comparator.comparingInt(MenuVO::getSort)));
                }
            }
            return result;
//            for (int i = 0; i < noChildrenResourceEntities.size(); i++) {
//                if (noChildrenResourceEntities.get(i).getParentId() == 0) {
//                    // 说明这个菜单是一级菜单 没有上一级菜单
//                    // 如果这里不为0 表示这个菜单是二级菜单 或者三级菜单 ParentId对应了属于哪个上级菜
//                    Menu resourceEntity = new Menu();
//                    // 把这个一级菜单取出来
//                    resourceEntity = noChildrenResourceEntities.get(i);
//                    List<Menu> resourceEntities = new ArrayList<>();
//                    // for把所有菜单过一遍
//                    for (int j = 0; j < noChildrenResourceEntities.size(); j++)
//                    {
//                        // 如果有菜单属于这个一级菜单
//                        if (Objects.equals(noChildrenResourceEntities.get(j).getParentId(), noChildrenResourceEntities.get(i).getMenuId())) {
//                            Menu resourceEntity2 = new Menu();
//                            // 取出这个二级菜单
//                            resourceEntity2 = noChildrenResourceEntities.get(j);
//                            resourceEntities.add(resourceEntity2);
//                        }
//                    }
//                    resourceEntity.setChild(resourceEntities);
//                    resourceEntityList.add(resourceEntity);
//                }
//            }
        }
//         下面是根据资源的sort进行排序 升序排列 这样左侧菜单就会按照升序排列
        Collections.sort(resourceEntityList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return o1.getSort().compareTo(o2.getSort());
            }
        });
        return null;
    }
}
